﻿namespace Leetcode.N0449.V1;

// 前序遍历
public class Codec
{
    public string serialize(TreeNode root)
    {
        IList<int> list = new List<int>();
        this.serialize(root, list);
        return string.Join(",", list);
    }

    private void serialize(TreeNode node, IList<int> list)
    {
        if (node == null)
        {
            return;
        }
        list.Add(node.val);
        serialize(node.left, list);
        serialize(node.right, list);
    }

    public TreeNode deserialize(string data)
    {
        if (string.IsNullOrEmpty(data))
        {
            return null;
        }
        var vals = data.Split(",").Select(i => int.Parse(i)).ToArray();
        var index = 0;
        return this.deserialize(vals, ref index, int.MinValue, int.MaxValue);
    }

    private TreeNode deserialize(int[] vals, ref int index, int min, int max)
    {
        if (index >= vals.Length || vals[index] < min || vals[index] > max)
        {
            return null;
        }
        var val = vals[index];
        var treeNode = new TreeNode(val);
        index++;
        treeNode.left = this.deserialize(vals, ref index, min, val);
        treeNode.right = this.deserialize(vals, ref index, val, max);
        return treeNode;
    }

}